package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alpha.bom.ExamResponse;
import com.alpha.dao.ExamDao;
import com.alpha.dao.ExamResponseDao;

/**
 * Servlet implementation class ExamReportServlet
 */
@WebServlet("/ExamReportServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class ExamReportServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(ExamReportServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExamReportServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		int exam_id;
		String exam_name = null;
		ArrayList<ExamResponse> exam_responses = new ArrayList<ExamResponse>();

		if(request.getParameter("exam_id")!=null){
			exam_id = Integer.parseInt(request.getParameter("exam_id"));
			ExamResponseDao rDao = new ExamResponseDao();
			ExamDao eDao = new ExamDao();
			//getting exam_responses by exam_id
			try {
				exam_name = eDao.retrieveExamById(exam_id).getExamName();
				exam_responses = rDao.retrieveExamResponseByExam(exam_id);
			} catch (NamingException e) {
				logger.error(e.getMessage());
				return;
			} catch (SQLException e) {
				logger.error(e.getMessage());
				return;
			}
			
			if(exam_responses!=null){
				request.setAttribute("exam_responses", exam_responses);
			}
			if(exam_name!=null){
				request.setAttribute("exam_name", exam_name);
			}
			
			RequestDispatcher dis=request.getRequestDispatcher("ExamReport.jsp");
            dis.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}

}
